package com.hengpeng.http;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <pre>
 * Http请求工具类
 * </pre>
 * @author chenjian
 * @version 1.0, 2012-12-19
 */
public class HttpRequestUtils
{
	private final static Log logger = LogFactory.getLog(HttpRequestUtils.class);

	private static int connectTimeOut = 30000;

	private static int readTimeout = 60000;

	/**
	 * <pre>
	 * 发送HTTP请求
	 * </pre>
	 * @param requestUrl 请求url
	 * @param content 请求类容
	 * @param method 请求方法
	 * @param connectTimeout 连接超时时间
	 * @param readTimeout 读超时时间
	 * @param encode 请求编码
	 * @return 响应内容
	 */
	private static String connect(String requestUrl, String content, String method, String encode)
	{
		URL url = null;
		HttpURLConnection urlConn = null;
		BufferedWriter bw = null;
		BufferedReader br = null;
		OutputStream out = null;
		String responseContent = null;
		try
		{
			url = new URL(requestUrl);
			urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setRequestProperty("User-Agent", "Mozilla/5.0");
			urlConn.setConnectTimeout(connectTimeOut);
			urlConn.setReadTimeout(readTimeout);
			if (content != null && !content.equalsIgnoreCase(""))
			{
				urlConn.setDoOutput(true);// 设置是否向httpUrlConnection输出,默认为false
				out = urlConn.getOutputStream();
				bw = new BufferedWriter(new OutputStreamWriter(out, encode));
				bw.write(content);
				bw.flush();
				bw.close();
				out.close();
			}
			urlConn.connect();
			br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), encode));
			StringBuffer sb = new StringBuffer();
			char[] re = new char[1024];
			int len = 0;
			while ((len = br.read(re)) != -1)
			{
				sb.append(re, 0, len);
			}
			responseContent = sb.toString();
			br.close();
		}
		catch (IOException ex)
		{
			logger.error("连接URL{" + requestUrl + "}时遇到网络故障, 异常消息{" + ex.getMessage() + "}");
		}
		finally
		{
			if (urlConn != null)
			{
				urlConn.disconnect();
			}
			bw = null;
			out = null;
			br = null;
			urlConn = null;
			url = null;
		}
		return responseContent;
	}

	private static String joinParameters(Map<String, String> parameters, String encode)
	{
		StringBuffer params = new StringBuffer();
		try
		{
			for (Iterator<Entry<String, String>> iter = parameters.entrySet().iterator(); iter.hasNext();)
			{
				Entry<String, String> element = iter.next();
				params.append(element.getKey());
				params.append("=");

				params.append(URLEncoder.encode(element.getValue().toString(), encode));

				params.append("&");
			}
			if (params.length() > 0)
			{
				params = params.deleteCharAt(params.length() - 1);
			}
		}
		catch (UnsupportedEncodingException e)
		{
			throw new RuntimeException(e);
		}
		return params.toString();
	}

	private static String request(String requestUrl, Map<String, String> parameters, String method, String encode)
	{
		if (parameters == null || parameters.size() <= 0)
		{
			return connect(requestUrl, null, method, encode);
		}
		return connect(requestUrl, joinParameters(parameters, encode), method, encode);
	}

	public static String post(String requestUrl, Map<String, String> parameters, String encode)
	{
		return request(requestUrl, parameters, "POST", encode);
	}

	public static String get(String requestUrl, Map<String, String> parameters, String encode)
	{
		requestUrl += "?" + joinParameters(parameters, encode);
		return request(requestUrl, null, "GET", encode);
	}

	public static void main(String[] args) throws Exception
	{
		/*Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("a", "aaaaaaa陈健");
		String text = post("http://localhost:8088/aaa", parameters, "UTF-8");
		System.out.println(text);*/
		
		String tt = "http://220.231.142.213:7081/jbhlottery/login.htm";
		
		System.out.println(URLEncoder.encode(tt,"utf-8"));
	}
}
